import http from 'http';
import path from "path";
import express from 'express';
import cookieParser from 'cookie-parser';
import session from 'express-session';
import ConnectMongo from 'connect-mongo';
import api from './src/api';
import page from './src/page';
let MongoStore = ConnectMongo(session);
const {SERVER_PORT, MONGO_URL, MONGO_PORT, MONGO_USER, MONGO_PASSWORD} = process.env;
let PORT = SERVER_PORT * 1;

let app = express();
app.use(cookieParser('foo'));
app.use(session({
    secret: 'foo',
    name: 'bbs.wison.com',
    cookie: {
        maxAge: 60 * 60 * 24 * 365 * 30
    },
    resave: false,
    saveUninitialized: true,
    store: new MongoStore({
        url: `mongodb://${MONGO_USER}:${MONGO_PASSWORD}@${MONGO_URL}:${MONGO_PORT}/session?authSource=admin`,
        collection: 'ima'
    })
}));
app.use('/static', express.static(path.resolve(process.cwd(), 'static')));
app.use('/api', api);
app.use('/', page);

let server = http.createServer(app)
    .listen(PORT)
    .on('error', error => {
        if (error.syscall !== 'listen') {
            throw error;
        }
        let bind = typeof PORT === 'string' ? 'Pipe ' + PORT : 'Port ' + PORT;
        switch (error.code) {
            case 'EACCES':
                console.error(bind + ' requires elevated privileges');
                process.exit(1);
                break;
            case 'EADDRINUSE':
                console.error(bind + ' is already in use');
                process.exit(1);
                break;
            default:
                throw error;
        }
    })
    .on('listening', () => {
        let addr = server.address();
        let bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port;
        console.log(`Server is running on  `, `${bind}`);
    });